package pyip.lib.mixtool.util.temp;

import java.text.SimpleDateFormat;
import java.util.List;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 转换器
 * @author shiwei
 */
public class Convertor {

    private static ObjectMapper mapper = new ObjectMapper();

    public static final String DATEFORMAT_YMDHMS = "yyyy-MM-dd HH:mm:ss";
    public static final String DATEFORMAT_YMDHM = "yyyy-MM-dd HH:mm";

    static {
        // 反序列化时忽略掉多余的属性
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        mapper.setDateFormat(new SimpleDateFormat(DATEFORMAT_YMDHMS));
    }

    /**
     * 将对象转换成json格式字符串
     * @param object
     * @return
     * @throws JsonProcessingException
     */
    public static String toJson(Object object) {
        try {
            return mapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            throw new SystemException(ExceptionEnum.jsonConvert, e);
        }
    }

    /**
     * 从json格式字符串转换成对象
     * @param json
     * @param clazz
     * @return
     * @throws Exception
     */
    public static <T> T fromJson(String json, Class<T> clazz) {
        try {
            return (T) mapper.readValue(json, clazz);
        } catch (Exception e) {
            throw new SystemException(ExceptionEnum.jsonConvert, e);
        }
    }

    public static <T> List<T> fromJsonList(String json, Class<T> clazz) {
        JavaType t = mapper.getTypeFactory().constructParametricType(List.class, clazz);
        try {
            return mapper.readValue(json, t);
        } catch (Exception e) {
            throw new SystemException(ExceptionEnum.jsonConvert, e);
        }
    }

}
